package io.lvdaxian.mybatis19.scripting.defaults;

import io.lvdaxian.mybatis19.builder.SqlSourceBuilder;
import io.lvdaxian.mybatis19.mapping.BoundSql;
import io.lvdaxian.mybatis19.mapping.SqlSource;
import io.lvdaxian.mybatis19.scripting.xmltags.DynamicContext;
import io.lvdaxian.mybatis19.scripting.xmltags.SqlNode;
import io.lvdaxian.mybatis19.session.Configuration;

import java.util.HashMap;

/**
 * 源sql 的 具体实现
 *
 * @author lihh
 */
public class RawSqlSource implements SqlSource {
  
  private final SqlSource sqlSource;
  
  public RawSqlSource(Configuration configuration, SqlNode rootSqlNode, Class<?> parameterType) {
    this(configuration, getSql(configuration, rootSqlNode), parameterType);
  }
  
  public RawSqlSource(Configuration configuration, String sql, Class<?> parameterType) {
    SqlSourceBuilder sqlSourceParser = new SqlSourceBuilder(configuration);
    Class<?> clazz = parameterType == null ? Object.class : parameterType;
    sqlSource = sqlSourceParser.parse(sql, clazz, new HashMap<>());
  }
  
  @Override
  public BoundSql getBoundSql(Object parameterObject) {
    return sqlSource.getBoundSql(parameterObject);
  }
  
  private static String getSql(Configuration configuration, SqlNode rootSqlNode) {
    DynamicContext context = new DynamicContext(configuration, null);
    rootSqlNode.apply(context);
    return context.getSql();
  }
}
